package org.jeecg.modules.demo.util;

import com.aliyun.ocr_api20210707.models.RecognizeInvoiceResponse;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

@Component
public class TicketUtil {
    private com.aliyun.ocr_api20210707.Client ocrclient;

    private com.aliyun.teautil.models.RuntimeOptions runtime;
    @PostConstruct
    public void init() throws Exception {
        this.ocrclient = createClient();
    }

    public static com.aliyun.ocr_api20210707.Client createClient() throws Exception {
        com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setCredential(credential);
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.ocr_api20210707.Client(config);
    }

    public String getInvoiceByOCR(InputStream inputStream) throws Exception {
        com.aliyun.ocr_api20210707.models.RecognizeInvoiceRequest recognizeInvoiceRequest = new com.aliyun.ocr_api20210707.models.RecognizeInvoiceRequest()
                .setBody(inputStream);
        this.runtime = new com.aliyun.teautil.models.RuntimeOptions();
        // 复制代码运行请自行打印 API 的返回值
        RecognizeInvoiceResponse ocrrsp = ocrclient.recognizeInvoiceWithOptions(recognizeInvoiceRequest, runtime);
        return ocrrsp.getBody().getData();
    }

    public static HttpURLConnection getFileInputStreamWithoutClosing(String url, Map<String, String> headers) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();

        // 禁用自动重定向（可选）
        connection.setInstanceFollowRedirects(false);

        // 设置请求方法
        connection.setRequestMethod("GET");

        // 添加头部信息
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }

        // 获取响应码
        int responseCode = connection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            return connection; // 注意：调用者必须手动关闭 InputStream
        } else {
            connection.disconnect(); // 失败时关闭连接
            throw new IOException("Failed to download file. HTTP error code: " + responseCode);
        }
    }
}
